import React, { useRef, useEffect, useState } from 'react'
import flvjs from 'flv.js'
import './player.scss'

const VideoPlayer = ({ url, id }) => {
  const videoRef = useRef(null)
  const flvPlayerRef = useRef(null)

  useEffect(() => {
    if (flvjs.isSupported() && url) {
      flvPlayerRef.current = flvjs.createPlayer({
        type: 'flv',
        url,
        isLive: true,
      })
      flvPlayerRef.current.attachMediaElement(videoRef.current)
      flvPlayerRef.current.load()
    }

    return () => {
      if (flvPlayerRef.current) {
        flvPlayerRef.current.unload()
        flvPlayerRef.current.detachMediaElement()
        flvPlayerRef.current.destroy()
      }
    }
  }, [url])

  return (
    <div className="video-container">
      <video ref={videoRef} controls width="100%" id={`flv-video-${id}`} />
    </div>
  )
}

const MultiFlvPlayer = ({ videoUrls }) => {
  return (
    <div className="multi-video-grid">
      {videoUrls.map((url, index) => (
        <VideoPlayer key={`player-${index}`} url={url} id={index} />
      ))}
    </div>
  )
}

export default MultiFlvPlayer
